package org.nativejpa.transaction;

import org.apache.commons.logging.LogFactory;
import org.apache.commons.logging.Log;
import org.objectweb.jotm.Jotm;
import org.objectweb.jotm.TimerManager;

import javax.transaction.TransactionManager;
import javax.naming.Context;
import javax.naming.NamingException;
import java.util.Properties;

/**
 * @author <a href="mailto:jfox.young@gmail.com">Young Yang</a>
 * @create 2009-3-17 17:12:41
 */
public class JOTMTransactionManagerFactory extends TransactionManagerFactory {

    protected final static Log log = LogFactory.getLog(JOTMTransactionManagerFactory.class);

    private static Jotm jotm;

    private int DefaultTransactionTimeout = 60; // default as JOTM

    public JOTMTransactionManagerFactory() {
        super();
    }

    public String getVendor() {
        return "JOTM";
    }

    public Properties getProperties() {
        return null;
    }

    protected TransactionManager getVendorTransactionManager() {
        return jotm.getTransactionManager();
    }

    public void init() {
        try {
            jotm = new Jotm(true, false);

            //FIXME 删除 carol 注册的全局变量 ServerConfiguration#124
            System.clearProperty(Context.URL_PKG_PREFIXES);
        }
        catch (NamingException e) {
            throw new RuntimeException("Could not initialize JOTM!", e);
        }
        log.info("JTA TransactionManager initalized.");
    }

    public void shutdown() {
        log.debug("postUnregister");
        // 需要调用 stop 方法，以停止 jotm 的线程，使程序能正常终止
        jotm.stop();
        // stop JOTM Timer Thread
        TimerManager.stop();
    }

    public int getDefaultTransactionTimeout() {
        return DefaultTransactionTimeout;
    }

    protected void setDefaultTransactionTimeout(int defaultTransactionTimeout) {
        DefaultTransactionTimeout = defaultTransactionTimeout;
    }
}
